package cn.sytton.taffe.framework.response;

import cn.sytton.taffe.framework.log.LogWriter;
import cn.sytton.taffe.framework.util.JsonUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 统一处理所有api返回结果
 *
 * @author skyrock
 */
@ControllerAdvice
public class ResponseBodyHandler implements ResponseBodyAdvice<Object> {

    @Resource
    private LogWriter logWriter;

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        logWriter.logEnd(body);
        if (body instanceof String){
            //返回String时,需要把封装好的ResponseResult仍然转成String,否则报错ResponseResult cannot be cast to java.lang.String
            //https://blog.csdn.net/weixin_45176654/article/details/109689869
            return JsonUtil.getString(ResponseResult.success(body));
        } else if (body instanceof ResponseResult){
            return body;
        } else if (request.getURI().getPath().startsWith("/v3/api-docs")) {
            return body;
        } else {
            return ResponseResult.success(body);
        }
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
}
